package com.free.company.member.service;

import com.alibaba.fastjson.JSONObject;
import com.foxinmy.weixin4j.cache.MemoryCacheStorager;
import com.foxinmy.weixin4j.model.Token;
import com.foxinmy.weixin4j.util.DateUtil;
import com.foxinmy.weixin4j.util.DigestUtil;
import com.foxinmy.weixin4j.util.MapUtil;
import com.foxinmy.weixin4j.util.RandomUtil;
import com.free.common.vo.ResultModel;
import com.free.ext.httpclient.HttpClientUtil;
import com.free.ext.httpclient.HttpConfig;
import com.free.ext.httpclient.utils.SSLs;
import com.free.ext.logger.FreeLogger;
import com.free.ext.logger.FreeLoggerFactory;
import com.free.ext.wechat.qy.QyWxProxy;
import com.free.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class JsTicketService extends CommonService {

    private static final FreeLogger LOG  = FreeLoggerFactory.getLogger((Class)JsTicketService.class);

    private static final MemoryCacheStorager<Token> memeoryCacheStorager = new MemoryCacheStorager();;
    private static final String RES_KEY_TICKET = "ticket";
    private static final String KEY_JS_TICKET = "key_js_ticket";
    private static final long TICKET_TIME = 5400000L;
    private static final String JS_TICKET = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=%s";
    private static final String APPID = "wx37870b4a0ffe27a9";

    private String getTicket() {
        LOG.info("获得token");
        Token cacheToken = JsTicketService.memeoryCacheStorager.lookup(KEY_JS_TICKET);
        if (cacheToken != null) {
            LOG.info("直接使用内存，返回：{}", (Object)cacheToken.getAccessToken());
            return cacheToken.getAccessToken();
        }
        LOG.info("需要获得token");
        try {
            QyWxProxy proxy = getProxy(APPID);
            if(proxy == null){
                return "";
            }
            String asccessToken = proxy.getTokenManager().getAccessToken();
            LOG.info("获得TOKEN{}信息",asccessToken);
            String reqUrl = String.format(JS_TICKET, asccessToken);
            String resStr = HttpClientUtil.get(HttpConfig.custom().sslProtocol(SSLs.SSLProtocolVersion.TLSv1_2).url(reqUrl));
            LOG.info("jsticketToken结果:{}", resStr);
            final Map resMap = (Map) JsonUtils.unsearlize(resStr, (Class)Map.class);
            if (resMap.get("errcode").toString().equals("0")) {
                cacheToken = new Token(resMap.get(RES_KEY_TICKET).toString(), TICKET_TIME);
                memeoryCacheStorager.caching(KEY_JS_TICKET, cacheToken);
                return cacheToken.getAccessToken();
            }
            return "";
        }
        catch (Exception ex) {
            return "";
        }
    }

    public ResultModel getSignString(final String url) {
        final String tokenStr = this.getTicket();
        if (StringUtils.isEmpty(tokenStr)) {
            return ResultModel.failure();
        }
        LOG.info("请求得URL：", url);
        final Map<String, String> signMap = new HashMap<String, String>();
        final String timestamp = DateUtil.timestamp2string();
        final String noncestr = RandomUtil.generateString(24);
        signMap.put("timestamp", timestamp);
        signMap.put("noncestr", noncestr);
        signMap.put("jsapi_ticket", tokenStr);
        signMap.put("url", url);
        final String sign = DigestUtil.SHA1(MapUtil.toJoinString(signMap, false, false));
        final JSONObject config = new JSONObject();
        config.put("appId", APPID);
        config.put("timestamp", timestamp);
        config.put("nonceStr", noncestr);
        config.put("signature", sign);
        LOG.info("URL信息{}", config.toJSONString());
        return ResultModel.success(config);
    }

}
